#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUF_SIZE 1024

int main(int argc, char *argv[])
{
	int inputFd, outputFd, openFlags;
	mode_t filePerms;
	ssize_t numRead;
	char buf[BUF_SIZE];

	if (argc != 3 || strcmp(argv[1], "--help") == 0) {
		printf("wrong argument!\n");
		exit(1);
	}

	/* open and input and output files */

	inputFd = open(argv[1], O_RDONLY);
	if (inputFd == -1) {
		printf("open input file err\n");
		exit(1);
	}

	openFlags = O_CREAT | O_WRONLY | O_TRUNC;
	filePerms = S_IRUSR | S_IWUSR | S_IRGRP |
				S_IROTH | S_IWOTH; /* rw-rw-rw*/
	outputFd = open(argv[2], openFlags, filePerms);
	if (outputFd == -1) {
		printf("open output file err\n");
		exit(0);
	}

	/* transfer */
	while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0)
		if (write(outputFd, buf, numRead) != numRead) {
			printf("couldn't write whole buffer\n");
			exit(1);
		}

	if (numRead == -1) {
		printf("transfer read file err\n");
		exit(1);
	}

	if (close(inputFd) == -1) {
		printf("close file err\n");
		exit(1);
	}

	if (close(outputFd) == -1) {
		printf("close output file err\n");
		exit(1);
	}
		
	return 0;
}
